import request from "@/utils/request.js"
import {
	getOrderInfo
} from "@/api/index.js"
import {
	messAllUnreadNum
} from "@/api/mine.js"
import permision from "@/js_sdk/wa-permission/permission.js"
export function getPhoneInfo() {
	let systemInfo = uni.getSystemInfoSync()
	uni.setStorageSync('systemInfo', systemInfo)
}
export function uploadFile(tempFilePaths, data) {
	console.log(tempFilePaths, data, '9999')
	uni.showLoading({
		title: '上传中',
		mask: true
	})
	let promise = new Promise(function(resolve, reject) {
		uni.uploadFile({
			url: request.baseUrl + '/file/syncUpload', //syncUpload
			header: {
				Authorization: uni.getStorageSync('token') ? 'Bearer ' + uni.getStorageSync('token') : ''
			},
			filePath: tempFilePaths[0],
			name: 'file',
			formData: data || {},
			success: (uploadFileRes) => {
				console.log("上传文件", JSON.parse(uploadFileRes.data));
				if (JSON.parse(uploadFileRes.data).code == 100000) {
					resolve(JSON.parse(uploadFileRes.data).data)
				} else {
					uni.showToast({
						icon: 'none',
						title: JSON.parse(uploadFileRes.data).msg,
						duration: 2000
					});
					if (JSON.parse(uploadFileRes.data).code == 900002) {
						setTimeout(() => {
							uni.navigateTo({
								url: '/pages/login/login'
							})
						}, 2000)
					}
				}
			},
			fail: (err) => {
				uni.showToast({
					title: '上传失败，请稍后重试',
					icon: 'none'
				})
			},
			complete: () => {
				uni.hideLoading()
			}
		});
	})
	return promise
}
export function previewImg(imgArr, idx) {
	uni.previewImage({
		current: idx ? idx : 0,
		urls: imgArr,
		success() {
			uni.setStorageSync('previewImg', true)
		}
	});
}
// 检测是否有开通权限
export async function requestAndroidPermission(permisionID) {
	let result = ''
	if (uni.getStorageSync('systemInfo').platform == 'ios') {
		result = permision.judgeIosPermission(permisionID) //判断iOS上是否给予位置权限，有权限返回true，否则返回false
	} else {
		result = await permision.requestAndroidPermission(permisionID)
	}
	console.error("权限==", result)
	if (result !== 1 || result === false) {
		uni.showToast({
			title: '检测到您未开通相关权限，将为您打开设置界面',
			icon: 'none',
			duration: 3000
		})
		setTimeout(() => {
			permision.gotoAppPermissionSetting()
		}, 3000)
	}
	return result
}
export function chooseImg(count) {
	let promise = new Promise(function(resolve, reject) {
		// #ifdef APP-PLUS
		let permisionString = ''
		if (uni.getStorageSync('systemInfo').platform == 'ios') {
			permisionString = 'photoLibrary'

		} else {
			permisionString = 'android.permission.READ_EXTERNAL_STORAGE'
		}
		requestAndroidPermission(permisionString).then((status) => {
			if (status !== 1 || status === false) {
				return
			}
			uni.chooseImage({
				count: count, //默认9
				sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
				sourceType: ['album'], //['album','camera'],先只留一个要不然安卓的权限不好做
				success: (res) => {
					console.log(res);
					// 判断图片大小
					let overSize = []
					res.tempFiles.forEach((item) => {
						if (item.size > 10 * 1024 * 1024) {
							overSize.push(item.name)
						}
					})
					if (overSize.length > 0) {
						uni.showToast({
							title: `您选择的名为 ${overSize.join(',')}的图片已经超出了10M大小！`,
							icon: 'none'
						})
						return
					} else {
						let files = res.tempFilePaths
						resolve(files)
					}
				}
			});
		})
		// #endif
		// #ifdef MP
		// 小程序基础库自2.21.0开始不再维护wx.chooseImage 所以用media
		uni.chooseMedia({
			count: count,
			mediaType: ['image'],
			sourceType: ['album'],
			success(res) {
				console.log(res);
				// 判断图片大小
				let overSize = []
				res.tempFiles.forEach((item) => {
					if (item.size > 10 * 1024 * 1024) {
						overSize.push(item.tempFilePath)
					}
				})
				if (overSize.length > 0) {
					uni.showToast({
						title: `您选择的图片中有超出了10M大小的，请重新选择！`,
						icon: 'none'
					})
					return
				} else {
					let files = []
					res.tempFiles.forEach((item) => {
						files.push(item.tempFilePath)
					})
					// let files=res.tempFiles[0].tempFilePath
					console.error("上传", files)
					resolve(files)
				}
			}
		})
		// #endif
		// #ifdef H5
		uni.chooseImage({
			count: count, //默认9
			sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
			sourceType: ['album'], //['album','camera'],先只留一个要不然安卓的权限不好做
			success: (res) => {
				console.log(res);
				// 判断图片大小
				let overSize = []
				res.tempFiles.forEach((item) => {
					if (item.size > 10 * 1024 * 1024) {
						overSize.push(item.name)
					}
				})
				if (overSize.length > 0) {
					uni.showToast({
						title: `您选择的名为 ${overSize.join(',')}的图片已经超出了10M大小！`,
						icon: 'none'
					})
					return
				} else {
					let files = res.tempFilePaths
					resolve(files)
				}
			}
		});
		// #endif

	})
	return promise
}
// 检查是否更新版本
export function updateVersion(newV) {
	let promise = new Promise(function(resolve, reject) {
		// 热更新不会更新app的版本号
		// 这里用一个常量定义（每次修改版本号将设置里面的版本号手动更新）
		let realVersion = newV.version,
			that = this;
		try {
			//plus.runtime.getProperty(),获取本机安装的版本，具体使用请参照如下链接
			plus.runtime.getProperty(plus.runtime.appid, function(widgetInfo) {
				let currentVersion = Number(widgetInfo.version.replace(/\./g, "")); //获取当前版本号
				let system = uni.getSystemInfoSync().platform,
					systemType = 1;
				if (system === 'ios') systemType = 2;
				console.log('版本号', currentVersion, system, widgetInfo)
				if (realVersion > currentVersion) {
					let versionData = Object.assign(newV, {
						system
					})
					resolve(versionData)
				}
			})
		} catch (e) {
			console.log('error===>', e)
		}
	})
	return promise

}
// 判断是否为disagreemode ，如果是引导用户同意隐私政策
export function modeJudge() {
	let promise = new Promise(function(resolve, reject) {
		if (!plus.runtime.isAgreePrivacy()) {
			let options = {
				success: function(response) {
					console.error("success  " + JSON.stringify(response));
					if (response.code == 1) {
						//用户已同意隐私政策，可以使用其它业务功能
						// 如果项目中使用了 map、push、Statistic，或者设置loadNativePlugins为false时，用户选择同意隐私政策协议后需要调用plus.runtime.restart重启应用才能生效！
						// plus.runtime.restart();
						getPhoneInfo()
						resolve(true)
					} else {
						//用户未同意隐私政策，仍然运行disagreeMode模式，不可以使用其它业务功能
						resolve(false)
					}
				},
				fail: function(response) {
					console.error("fail  " + JSON.stringify(response));
					resolve(false)
				}
			};
			//弹出隐私政策协议框，引导用户同意隐私政策
			plus.runtime.showPrivacyDialog(options);
		} else {
			resolve(true)
		}
	})
	return promise
}
// 是否启用下拉刷新（解决在一个页面，弹框的滚动会触发页面的下拉刷新）
export function isPullDown(isPull) {
	//获取当前 Webview 窗口对象
	const pages = getCurrentPages();
	const page = pages[pages.length - 1];
	const currentWebview = page.$getAppWebview();
	//根据状态值来切换禁用/开启下拉刷新
	currentWebview.setStyle({
		pullToRefresh: {
			support: isPull,
			// style: plus.os.name === 'Android' ? 'circle' : 'default',
			style: 'circle'
		}
	});
}
// 获取订单信息吊起支付
export function getOrderAndPay(param) {
	let promise = new Promise(function(resolve, reject) {
		//TO DO 获取订单信息的接口
		let newParam = {
			goodsId: param.id,
			payWay: param.payWay,
			goodsType: param.orderType, // 支付的由头  2查看最佳答案；3赏金；4、活动，5、查看专业详情支付，6、发布找人，7、购买择校报告 8、调剂信息单条支付 9、调剂信息全部支付
			payProduct: param.payProduct, ////1小程序；2App
		}
		// 调剂信息单条支付增加传参
		if (param.orderType == 8) {
			newParam.schoolCode = param.schoolCode;
			newParam.collegeCode = param.collegeCode;
			newParam.majorCode = param.majorCode
		}
		if (param.orderType == 4) {
			newParam.attach = {
				teamId: param.groupId
			}
		}
		console.log('支付===', newParam, param)
		getOrderInfo(newParam).then((res) => {
			console.log('resOrder: ', res);
			if (res.code == 100000) {
				// #ifndef MP
				let payInfo = Object.assign({
					'package': res.data.wechatPayResponse.packageStr,
					'prepayid': res.data.wechatPayResponse.prepayId,
					'timestamp': res.data.wechatPayResponse.timeStamp
				}, res.data.wechatPayResponse)
				delete payInfo.packageStr
				delete payInfo.prepayId
				delete payInfo.timeStamp
				console.error('res', res, payInfo)
				uni.requestPayment({
					"provider": "wxpay",
					//微信、支付宝订单数据 【注意微信的订单信息，键值应该全部是小写，不能采用驼峰命名】
					"orderInfo": payInfo,
					success(res1) {
						resolve(true)
					},
					fail(e) {
						console.error("调用支付失败", e)
						if (e.errMsg.indexOf('User canceled') != -1 || e.errMsg.indexOf("fail [Payment微信:-2]") != -1) {
							uni.showToast({
								title: '取消支付',
								icon: 'none'
							})
							return
						} else {
							uni.showToast({
								title: '调用支付失败',
								icon: 'none'
							})
						}
					}
				})
				// #endif
				// #ifdef MP
				uni.requestPayment({
					"appId": res.data.wechatPayResponse.appid,
					// "provider": "wxpay",
					// "orderInfo":param,
					"timeStamp": res.data.wechatPayResponse.timeStamp,
					"nonceStr": res.data.wechatPayResponse.noncestr,
					"package": res.data.wechatPayResponse.packageStr,
					"signType": "RSA",
					"paySign": res.data.wechatPayResponse.sign,
					success(res1) {
						console.log('成功支付', res)
						resolve(res)
					},
					fail(e) {
						console.log("调用支付失败", e)
						if (e.errMsg.indexOf('User canceled') != -1 || e.errMsg.indexOf("fail [Payment微信:-2]") != -1 ||
							e.errMsg.indexOf("fail cancel") != -1) {
							uni.showToast({
								title: '取消支付',
								icon: 'none'
							})
							return
						} else {
							uni.showToast({
								title: '调用支付失败',
								icon: 'none'
							})
						}
					}
				})
				// #endif
			}
		}).catch((err) => {
			uni.hideLoading()
		})
	})
	return promise
}
// 查看最佳答案
export function payBeforeTip(param, tip, url) {
	let query = param ? param : {}
	query.money = query.money ? query.money : 1
	//type 2查看答案；3提问赏金
	query.type = query.type ? query.type : 2
	let showTip = tip ? tip : '查看最佳答案需要支付1元，是否确定查看？'
	if (param.isBestBuy && param.type == 2) {
		uni.navigateTo({
			url: `/pages/send/answer/answerDetail/answerDetail?id=${param.id}&quesTitle=${param.quesTitle}`
		})
		return
	}
	uni.showModal({
		title: '提示',
		content: showTip,
		success: (res) => {
			if (res.confirm) {
				uni.navigateTo({
					url: `${url?url:'/pages/order/order'}?query=${JSON.stringify(query)}`
				})
			} else if (res.cancel) {

			}
		}
	});
}
// 获取未读数量红点
export function getNoRead(callbackFun) {
	messAllUnreadNum().then((res) => {
		if (res.code == 100000) {
			let totalNum = Number(res.data.qaMessageUnReadTotal) + Number(res.data.systemMessageUnReadTotal) + Number(res
				.data.foundPersonMessageUnReadTotal)
			if (totalNum > 0) {
				uni.showTabBarRedDot({
					index: 3
				})
			} else {
				uni.hideTabBarRedDot({
					index: 3
				})
			}
			if (callbackFun) {
				callbackFun(totalNum)
			}
		}
	})
}
// 获取微信code
export function getWxCode() {
	let promise = new Promise(function(resolve, reject) {
		uni.login({
			provider: 'weixin', //使用微信登录
			success: (loginRes) => {
				console.error("微信code", loginRes.code);
				resolve(loginRes.code)
			},
			fail: (err) => {
				console.error('err', err)
				uni.showToast({
					title: '获取微信code失败',
					icon: 'none'
				})
				reject(err)
			}
		})
	})
	return promise
}

//获取抖音code
export function getDyCode(){
	let promise = new Promise(function(resolve, reject) {
		uni.login({
			provider: 'toutiao', //使用微信登录
			success: (loginRes) => {
				console.error("抖音code", loginRes.code);
				resolve(loginRes.code)
			},
			fail: (err) => {
				console.error('err', err)
				uni.showToast({
					title: '获取抖音code失败',
					icon: 'none'
				})
				reject(err)
			}
		})
	})
	return promise
}


// 小程序专用（用来计算状态栏高度以及胶囊高度的方法）
export function accountWxTopHeight(type) {
	console.log('状态栏高度', uni.getSystemInfoSync().statusBarHeight, wx.getMenuButtonBoundingClientRect().height)
	// 44是导航栏高度
	return uni.getSystemInfoSync().statusBarHeight + 44
}
// 未登录，跳转到登录的方法(此方法是已经判断未登录后执行的操作，不包含判断是否登录了)
export function navigateLoginPage(type) {
	// navigateLogin 此字段用来防止多次点击会多次跳转到登录页
	let pages = getCurrentPages()
	// console.error("未登录获取当前页的路由方便登录后返回",pages[pages.length - 1].$page.fullPath)
	// 存路径是用来判断跳转登录前在哪个页面，登录后跳转回去
	uni.setStorageSync('prePath', pages[pages.length - 1].$page.fullPath)
	if (uni.getStorageSync('token')) return
	if (uni.getStorageSync('navigateLogin')) return;
	uni.showToast({
		icon: 'none',
		title: '您未登录，请先登录',
		duration: 2000
	});
	// type=noJump的存在是用来判断我的页面的，我的页面不需要自动跳转登录
	if (type == 'noJump') return;
	uni.setStorageSync('navigateLogin', true)
	setTimeout(() => {
		uni.reLaunch({
			url: '/pages/login/login'
		})
	}, 1200)
}
// 获取当前日期
export function getNowDate(type) {
	let myDate = new Date()
	let year = myDate.getFullYear()
	let month = (myDate.getMonth() < 10 ? ('0' + (myDate.getMonth() + 1)) : myDate.getMonth() + 1)
	let day = myDate.getDate() < 10 ? ('0' + myDate.getDate()) : myDate.getDate()
	let hour = myDate.getHours() < 10 ? ('0' + myDate.getHours()) : myDate.getHours();
	let min = myDate.getMinutes() < 10 ? ('0' + myDate.getMinutes()) : myDate.getMinutes();
	let sec = myDate.getSeconds() < 10 ? ('0' + myDate.getSeconds()) : myDate.getSeconds();
	console.log('年月日', year, month, day)
	return type == 'all' ? `${year}-${month}-${day} ${hour}:${min}:${sec}` : `${year}-${month}-${day}`
}

// 防抖函数
let timeout = null
export function debounce(fn, wait) {
	if (timeout !== null) clearTimeout(timeout)
	timeout = setTimeout(fn, wait)
}

/**
 * 阿拉伯数字转中文数字，千亿位以下有效
 * @param num
 * @return {string}
 */
export function numberToChinese(num) {
	let chiNum = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
	let chiUni = ['', '十', '百', '千', '万', '亿', '十', '百', '千'];
	let num_str = num.toString();
	let count = num_str.length;
	let last_flag = true; //上一个 是否为0
	let zero_flag = true; //是否第一个
	let temp_num = null; //临时数字
	let chiStr = ''; //拼接结果
	if (count == 2) { //两位数
		temp_num = num_str[0];
		chiStr = temp_num == 1 ? chiUni[1] : chiNum[temp_num] + chiUni[1];
		temp_num = num_str[1];
		chiStr += temp_num == 0 ? '' : chiNum[temp_num];
	} else if (count > 2) {
		let index = 0;
		for (let i = count - 1; i >= 0; i--) {

			temp_num = num_str[i];

			if (temp_num == 0) {

				if (!zero_flag && !last_flag) {

					chiStr = chiNum[temp_num] + chiStr;
					last_flag = true;
				}

			} else {
				chiStr = chiNum[temp_num] + chiUni[index % 9] + chiStr;
				zero_flag = false;
				last_flag = false;
			}

			index++;
		}

	} else {

		chiStr = chiNum[num_str[0]];
	}

	return chiStr;
}